<template>
  <div>
    <FormContainer :column="4">
      <el-form ref="form" :model="formData" :rules="formRules" label-width="80px">
        <el-form-item prop="distributeMode" label="质检方式">
          <el-select v-model="formData.distributeMode" filterable @change="methodChangeHandle">
            <el-option :value="2" label="随机分配"></el-option>
            <el-option :value="1" label="手动分配"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </FormContainer>
    <div class="table-box">
      <div class="table-list-box">
        <el-table :data="stepData.litigants" header-row-class-name="table-list-header" tooltip-effect="dark" highlight-current-row>
          <!-- <el-table-column type="selection" align="center"></el-table-column> -->
          <el-table-column type="index" align="center" width="60" label="序号"></el-table-column>
          <el-table-column label="受检人" min-width="140">
            <template v-slot="{row}">
              <span>{{ row.operatorName }}({{ row.operator }})</span>
            </template>
          </el-table-column>
          <el-table-column label="质检人" min-width="140">
            <template v-slot="{row, column, $index}">
              <InspectionPersonSelect v-model="relationsView[$index]" :executors="executors" :row="row" :column="column" :index="$index" @clear="clearHandle($index)" @change="v=>changeHandle(v,row, column, $index)"></InspectionPersonSelect>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <ButtonGroup :button="['save', 'next', 'prev']" padding-top="10px" @next="nextHandle" @prev="prevHandle" @save="saveHandle"></ButtonGroup>
  </div>
</template>

<script>
import FormContainer from '@/components/FormContainer'
import ButtonGroup from './buttonGroup'
import InspectionPersonSelect from './inspectionPersonSelect'
import { qualityCheckProjectSaveRelations } from '@/api/inspection'
import { deepCopy } from '@/utils'
function relation(projectId, executor, executorName, executorBusinessGroupNo, executorBusinessGroupName, litigant, litigantName, litigantBusinessGroupNo, litigantBusinessGroupName) {
  return {
    executor,	// 执行人
    executorBusinessGroupName,	// 执行人业务组名称
    executorBusinessGroupNo, // 执行人业务组
    executorName, // 执行人姓名
    // id, // 质检操作人关系ID
    litigant, // 被执行人
    litigantBusinessGroupName, // 被执行人业务组名称
    litigantBusinessGroupNo, // 被执行人业务组
    litigantName, // 被执行人姓名
    projectId // 质检项目ID
  }
}
export default {
  name: 'InspectionWay',
  components: {
    FormContainer,
    ButtonGroup,
    InspectionPersonSelect
  },
  props: {
    stepData: {
      type: Object,
      default: () => ({})
    },
    next: {
      type: String,
      default: undefined
    },
    prev: {
      type: String,
      default: undefined
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        distributeMode: ''
      },
      formRules: {
        distributeMode: [{ required: true, message: '请选择质检方式', trigger: 'change' }]
      },
      executors: this.stepData.executors,
      relationsView: {},
      relations: {}
    }
  },
  watch: {
    stepData: {
      handler() {
        this.executors = this.stepData.executors
        // this.$set(this.formData, 'distributeMode', this.stepData.distributeMode)
        // this.methodChangeHandle(this.formData.distributeMode)
      },
      immediate: true
    }
  },
  mounted() {
    this.$set(this.formData, 'distributeMode', this.stepData.distributeMode)
    this.initData()
  },
  methods: {
    // 初始化
    initData() {
      const { litigants, executors, relations } = this.stepData
      const relationsView = {}
      const _relations = {}
      for (let i = 0; i < litigants.length; i++) {
        const v = litigants[i]
        let re
        for (re of relations) {
          if (re.litigant === v.operator) {
            break
          }
          re = undefined
        }
        if (!re) continue
        let exe
        for (exe of executors) {
          if (re.executor === exe.operator) {
            break
          }
          exe = undefined
        }
        if (exe) {
          relationsView[i] = exe
          _relations[i] = re
        }
      }
      this.relationsView = relationsView
      this.relations = _relations
    },
    // 分配
    methodChangeHandle(v) {
      this.relations = {}
      this.relationsView = {}
      if (v === '2' || v === 2) {
        this.randomAllocation()
      }
    },
    // 随机分配
    randomAllocation() {
      const { litigants } = this.stepData
      const length = this.executors.length
      for (let i = 0; i < litigants.length; i++) {
        const li = litigants[i]
        let n = i % length
        let ex = this.executors[n]
        while (li.operator === ex.operator) {
          n = Math.floor(Math.random() * length)
          ex = this.executors[n]
        }
        this.$set(this.relationsView, i, deepCopy(ex))
        this.changeHandle(ex, li, '', i)
      }
    },
    // 选项变化
    changeHandle(v, row, column, $index) {
      const { operator: executor, operatorName: executorName, businessGroupNo: executorBusinessGroupNo, businessGroupName: executorBusinessGroupName } = v
      const { operator: litigant, operatorName: litigantName, businessGroupNo: litigantBusinessGroupNo, businessGroupName: litigantBusinessGroupName } = row
      if (executor === litigant) {
        this.$message.warning('质检人和受检人不能是同一个人！')
        this.$nextTick(() => { this.relationsView[$index] = undefined })
        return
      }
      this.$set(this.relations, $index, relation(this.stepData.id, executor, executorName, executorBusinessGroupNo, executorBusinessGroupName, litigant, litigantName, litigantBusinessGroupNo, litigantBusinessGroupName))
    },
    // 清空质检人
    clearHandle($index) {
      this.$delete(this.relations, $index)
    },
    // 保存
    saveHandle() {
      return this.$refs.form.validate().then(() => {
        const relations = Object.values(this.relations)
        if (relations.length <= 0) {
          return this.$message.warning('请分配质检人！')
        }
        const data = {
          relations,
          id: this.stepData.id,
          distributeMode: this.formData.distributeMode
        }
        return qualityCheckProjectSaveRelations(data).then(res => {
          this.$message.success('保存成功！')
          this.$emit('on-refresh')
        })
      })
    },
    nextHandle() {
      this.$emit('input', this.next)
    },
    prevHandle() {
      this.$emit('input', this.prev)
    }
  }
}
</script>
